package com.water.bs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.water.bs.pojo.EmailCode;
import com.water.bs.service.EmailService;
import com.water.bs.service.OrgService;
import com.water.bs.service.UserService;
import com.water.bs.utils.MailUtil;
import com.water.bs.utils.NumberUtil;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.text.resources.FormatData;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

@RestController
@CrossOrigin
public class RegisterController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private NumberUtil numberUtil;
    @Autowired
    private OrgService orgService;
    @RequestMapping("/register")
    public JSON register(@RequestBody JSONObject registerInfo) {
        System.out.println("注册请求:" + registerInfo);
        Map<String,Object> registerUser = new HashMap<>();
        registerUser = registerInfo;
        String s = (String) registerInfo.get("password");
        registerUser.put("password",DigestUtils.md5DigestAsHex(s.getBytes()));
        JSONObject rs = new JSONObject();
        String userEmail = (String) registerUser.get("email");//用户注册的邮箱
        String userEmailCode = (String) registerInfo.get("emailCode"); //用户输入的验证码
        EmailCode emailCode = emailService.getEmailCode(userEmail); //通过用户邮箱获取验证码  包含了发送时间，验证码
        int emailRepeat = userService.isEmailRepeat(userEmail);
        if (emailRepeat>0){
            rs.put("state","5");
            rs.put("message","邮箱号已被注册!");
            return rs;
        }
        if (emailCode==null ){
            rs.put("state","6");
            rs.put("message","请获取邮箱验证码进行验证!");
            return rs;
        }
        if (emailCode.getCode().equals(userEmailCode) && mailUtil.emailCodeAble(emailCode.getSendTime())) { //验证码验证成功(验证码正确并且再有效期)
            String id = UUID.randomUUID().toString();
            System.out.println("UUID:" + id);
            registerUser.put("id",id);
            registerUser.put("point",0);
            registerUser.put("shoppoint",0);
            registerUser.put("role",1);
            String cityStr = StringUtils.join((Collection<String>) registerUser.get("city"), ',').replaceAll(",",""); //join方法把数组变成str 需要一个分隔符,最后再用replace把分隔符去了
            System.out.println(cityStr);
            registerUser.put("city",cityStr);
            String lowerCaseEmail = ((String) registerInfo.get("email")).toLowerCase();  //把注册时的邮箱 变成小写再存到数据库
            registerUser.put("email",lowerCaseEmail);
            System.out.println("user:" + registerUser);
            int i = userService.addUser(registerUser);
            if (i > 0) {//添加到数据库成功
                rs.put("state", "0");
                rs.put("message", "注册成功!");
                //注册成功后再把这个邮箱的注册验证码信息从验证码表中清除
                emailService.deleteEmailCode(userEmail);
            } else {//添加到数据库失败
                rs.put("state", "1");
                rs.put("message", "出现了一点问题,请稍后再试");
            }
        } else {//验证码验证不成功
            rs.put("state", "2");
            rs.put("message", "邮箱验证码错误或过期,请重新输入或再次获取!");
        }
        return rs;

    }
    @RequestMapping("/orgRegister1")
    public JSON orgRegister1(@RequestBody JSONObject orgRegisterInfo){
        JSONObject rs = new JSONObject();
        System.out.println("机构注册信息:"+orgRegisterInfo.get("orgRegisterInfo"));

        Map<String, Object> map = (Map<String, Object>) orgRegisterInfo.get("orgRegisterInfo");
//        {orgname=123, orgemail=694886886@QQ.COM, emailcode=178057, orgpassword=123}
        String s = (String) map.get("orgpassword");
        map.put("password",DigestUtils.md5DigestAsHex(s.getBytes()));
        System.out.println("orgreinfo转化map:"+map);
//        orgreinfo转化map:{orgname=123, orgemail=694886886@QQ.COM, emailcode=178057, orgpassword=123, password=202cb962ac59075b964b07152d234b70}
        String orgEmail = (String) map.get("orgemail");
        EmailCode emailCode = emailService.getEmailCode(orgEmail); //通过用户邮箱获取验证码  包含了发送时间，验证码
        String orgEmailCole = (String) map.get("emailcode"); //机构注册时填写的邮箱验证码
        int emailRepeat = orgService.isEmailRepeat(orgEmail);
        if (emailRepeat>0){
            rs.put("state","1");
            rs.put("message","邮箱号已拥有注册在内的机构!");
            return rs;
        }
        if (emailCode==null ){
            rs.put("state","2");
            rs.put("message","请获取邮箱验证码进行验证!");
            return rs;
        }
        if (emailCode.getCode().equals(orgEmailCole) && mailUtil.emailCodeAble(emailCode.getSendTime())) { //验证码验证成功(验证码正确并且再有效期)
            String orgid = UUID.randomUUID().toString();
            map.put("orgid",orgid);
            String lowerCaseEmail = ((String) map.get("orgemail")).toLowerCase();  //把注册时的邮箱 变成小写再存到数据库 统一
            map.put("orgemail",lowerCaseEmail);
            System.out.println("机构注册申请信息:" + map);
            int i = orgService.saveOrgRegInfo(map);
            if (i > 0) {//添加到数据库成功
                rs.put("state", "0");
                rs.put("message", "申请成功,等待管理员审批!");
                rs.put("id", orgid);
                //申请成功后再把这个邮箱的注册验证码信息从验证码表中清除
                emailService.deleteEmailCode(orgEmail);
            } else {//添加到数据库失败
                rs.put("state", "3");
                rs.put("message", "网络异常!");
            }
        } else {//验证码验证不成功
            rs.put("state", "4");
            rs.put("message", "邮箱验证码错误或过期,请重新输入或再次获取!");
        }
        return rs;
    }

        @RequestMapping("/orgRegisterApply")
        public JSON orgRegister(HttpServletRequest request) throws IOException { //接收前端formdata数据 有图片有字段
            JSONObject rs = new JSONObject();
            MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
            MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
            System.out.println("接收到的图片:"+file);
            Map<String, Object> map = new HashMap<>();
            if (file.isEmpty()||file==null){
                rs.put("state","5");
                rs.put("message","上传失败,请重新选择!");

            }
            System.out.println("接收到的注册信息1:"+params.getParameter("orgemail"));
            System.out.println("接收到的注册信息2:"+params.getParameter("orgpassword"));
            System.out.println("接收到的注册信息3:"+params.getParameter("orgname"));
            System.out.println("接收到的注册信息4:"+params.getParameter("orgemailCode"));

            String orgEmailCode = params.getParameter("orgemailCode");//注册填写的邮箱验证码
            String orgEmail = params.getParameter("orgemail").toLowerCase();
            EmailCode emailCode = emailService.getEmailCode(orgEmail);//通过邮箱获取验证码类  包含了发送时间，验证码
            int emailRepeat = orgService.isEmailRepeat(orgEmail);
            if (emailRepeat>0){
                rs.put("state","1");
                rs.put("message","邮箱号已拥有注册在内的机构!");

            }
            if (emailCode==null ){
                rs.put("state","2");
                rs.put("message","请获取邮箱验证码进行验证!");

            }
            String orgid = UUID.randomUUID().toString();
            if (emailCode.getCode().equals(orgEmailCode) && mailUtil.emailCodeAble(emailCode.getSendTime())) { //验证码验证成功(验证码正确并且再有效期)

                map.put("orgemail",orgEmail);//注册邮箱转化小写
                String s = (String) params.getParameter("orgpassword");
                map.put("orgpassword",DigestUtils.md5DigestAsHex(s.getBytes()));
                map.put("orgid",orgid);
                map.put("orgname",params.getParameter("orgname"));
                map.put("applystate",0); //初始状态0 等待审批
                map.put("createtime",System.currentTimeMillis()); //时间
                System.out.println("orgapplyMap:"+map);
                int i = orgService.saveOrgRegInfo(map);
                if (i > 0) {//添加到数据库成功
                    rs.put("state", "0");
                    rs.put("message", "申请成功,等待管理员审批!");
                    //申请成功后再把这个邮箱的注册验证码信息从验证码表中清除
                    emailService.deleteEmailCode(orgEmail);
                } else {//添加到数据库失败
                    rs.put("state", "3");
                    rs.put("message", "网络异常!");

                }
            } else {//验证码验证不成功
                rs.put("state", "4");
                rs.put("message", "邮箱验证码错误或过期,请重新输入或再次获取!");

            }
            //这里 把注册申请的 orgemail orgname orgpassword orgid存到申请表内 接着存photo

            try {
                InputStream is = file.getInputStream();
                byte[] photoFile = new byte[(int)file.getSize()];
                System.out.println(file.getSize());
                is.read(photoFile);
                map.put("photofile",photoFile);
                map.put("id",orgid);
                orgService.saveOrgApplyPhoto(map);

            } catch (IOException e) {
                e.printStackTrace();
            }
            return rs;
    }

}
